﻿using System;
using System.Windows.Forms;
using org.se.fs.presenter.Library;
using org.se.fs.presenter.View;

namespace org.se.fs.view
{
    public partial class FrmDatabaseConnection : Form, presenter.IView.IDatabaseConnection
    {
        #region Public Property Variable
        public string ServerHost
        {
            get { return txtServer.Text; }
            set { txtServer.Text = value; }
        }
        public string Username
        {
            get { return txtUsername.Text; }
            set { txtUsername.Text = value; }
        }
        public string Password
        {
            get { return txtPassword.Text; }
            set { txtPassword.Text = value; }
        }
        #endregion

        private readonly DatabaseConnection _presenter;
        private bool _isSuccess;

        public FrmDatabaseConnection()
        {
            InitializeComponent();
            _presenter = new DatabaseConnection(this);
            _presenter.OnTestConnectFinished += PresenterOnTestConnectFinished;
            _presenter.OnOkFinished += PresenterOnOkFinished;
        }

        public static bool FormShow()
        {
            using (var frmForm = new FrmDatabaseConnection())
            {
                frmForm.ShowDialog();
                return frmForm._isSuccess;
            }
        }

        private void FrmDatabaseConnectionLoad(object sender, EventArgs e)
        {
            _presenter.Initialize();
        }

        private void BtnTestClick(object sender, EventArgs e)
        {
            Enabled = false;
            _presenter.TestConnect();
        }

        private void BtnOkClick(object sender, EventArgs e)
        {
            Enabled = false;
            _presenter.Save();
        }

        private void BtnCloseClick(object sender, EventArgs e)
        {
            _isSuccess = false;
            Close();
        }

        void PresenterOnOkFinished(object source, FormEvent e)
        {
            Enabled = true;
            _isSuccess = true;
            Close();
        }

        void PresenterOnTestConnectFinished(object source, FormEvent e)
        {
            BeginInvoke((MethodInvoker)delegate { Enabled = true; });
            MessageBox.Show(e.Value.ToString());
        }
    }
}
